package cep.web.person.mapper;

import cep.model.entity.core.Floor;
import cep.model.entity.core.News;
import cep.model.entity.core.Person;
import cep.model.dao.CoreDao;
import cep.web.person.beans.FloorBean;
import cep.web.person.beans.PersonBean;
import cep.web.repo.NameHolder;
import cep.web.repo.NewsInfo;
import cep.web.repo.PersonBaseInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * User: golovin
 * Date: 23.06.13
 * Time: 2:02
 */
@Service
public class PersonMapper {
    @Autowired
    @Qualifier("commonDaoImplMock")
    private CoreDao coreDao;

    public void mapFloor(FloorBean bean) {
        int currentFloor = bean.getCurrentFloor();
        List<Floor> floorList = coreDao.getFloorList();
        bean.setFloorList(new ArrayList<NameHolder>());
        bean.setPersonList(new ArrayList<PersonBaseInfo>());
        for (Floor f: floorList) {
            bean.getFloorList().add(new NameHolder(f.getName(), f.getId()));
            if (f.getId() == currentFloor) {
                bean.setImageFloor(f.getImage());
                if (f.getPersonList() != null) {
                    for (Person p: f.getPersonList()) {
                        PersonBaseInfo pbi = new PersonBaseInfo();
                        pbi.setId(p.getId());
                        pbi.setFirstName(p.getFirstName());
                        pbi.setLastName(p.getLastName());
                        pbi.setX1(p.getPlace().getX1());
                        pbi.setY1(p.getPlace().getY1());
                        pbi.setX2(p.getPlace().getX2());
                        pbi.setY2(p.getPlace().getY2());
                        pbi.setImage(p.getImage());
                        bean.getPersonList().add(pbi);
                    }
                }
            }
        }
    }

    public void mapPerson(PersonBean bean) {
        Person p = coreDao.getPerson(bean.getBase().getId());
        bean.getBase().setFirstName(p.getFirstName());
        bean.getBase().setLastName(p.getLastName());
        bean.getBase().setImage(p.getImage());
    }

    public void mapNews(List<NewsInfo> newsInfoList) {
        newsInfoList.clear();
        List<News> newsList = coreDao.getNewsList();
        for (News n: newsList) {
            NewsInfo ni = new NewsInfo();
            ni.setId(n.getId());
            ni.setName(n.getName());
            ni.setDescription(n.getDescription());
            int cut = n.getDescription().indexOf("#cut");
            if (cut != -1) {
                ni.setCutDescription(n.getDescription().substring(0, cut));
            } else {
                ni.setCutDescription(n.getDescription());
            }
            ni.setImage(n.getImage());
            newsInfoList.add(ni);
        }
    }
}
